import { Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { AuthRequest, DecodedToken } from '../types/auth';
import config from '../config';
import { RedisService } from '../sdk/redis/RedisService';

export const JWT_SECRET = config.auth.JWT_SECRET;
const redis = new RedisService();
const USER_TOKEN_PREFIX = 'user_token:';

// 验证 Token 的中间件
export const verifyToken = async (req: AuthRequest, res: Response, next: NextFunction): Promise<void> => {
    const token = req.headers.authorization?.split(' ')[1];

    if (!token) {
        res.status(401).json({
            success: false,
            message: '未提供 Token'
        });
        return;
    }

    try {
        const decoded = jwt.verify(token, JWT_SECRET) as DecodedToken;
        
        // 验证 Redis 中是否存在用户数据
        const userKey = `${USER_TOKEN_PREFIX}${decoded.id}`;
        // const userData = await redis.get(userKey);

        // if (!userData) {
        //     res.status(401).json({
        //         success: false,
        //         message: 'Token 已过期，请重新登录'
        //     });
        //     return;
        // }

        req.user = decoded;
        next();
    } catch (error) {
        res.status(401).json({
            success: false,
            message: 'Token 无效或已过期'
        });
    }
};

// 白名单路由配置，支持正则表达式
const whiteListPatterns: (string | RegExp)[] = [
    '/api/login',
    '/api/captcha',
    '/app/home',
    '/app/mpWeixin/login',
    '/app/payment/notify',
    new RegExp('^/app/mpWeixin/.*$'),
    new RegExp('^/app/ocr/.*$'),
    new RegExp('^/app/upload/.*$'),
    new RegExp('^/app/dictionary/.*$'),
    new RegExp('^/app/content/.*$'),
    new RegExp('^/app/policy/.*$'),
    new RegExp('^/app/mp/.*$'),
    new RegExp('^/uploads/.*$'),
    new RegExp('^/html/.*$')
];

// 检查路径是否在白名单中
const isWhitelisted = (path: string): boolean => {
    return whiteListPatterns.some(pattern => {
        if (pattern instanceof RegExp) {
            return pattern.test(path);
        }
        return path.startsWith(pattern);
    });
};

// 全局验证中间件
export const globalAuthMiddleware = (req: AuthRequest, res: Response, next: NextFunction): void => {
    // 检查请求路径是否在白名单中
    if (isWhitelisted(req.path)) {
        return next();
    }

    // 非公开路由进行 token 验证
    verifyToken(req, res, next);
}; 